import { defineStore } from "pinia"
import type { UserType } from "./types"
import { ImitateHttp, localSetItem, localGetItem } from "@/utils";


const userStore = defineStore("user", {
    //定义了状态userInfo表示当前已登录的用户
    state: () => ({
        userInfo: null as UserType | null
    }),
    //创建修改用户的方法
    actions: {
        setUser(user: UserType) {
            this.userInfo = user;
            localStorage.setItem("login_user", JSON.stringify(user));
        },
        //注册方法
        register(form: UserType) {
            return ImitateHttp((s, f) => {
                form.user_id = parseInt(form.phone.slice(-4));
                localSetItem("regis_user", form);
                s("ok");
            });
        },
        //登录方法
        login(form: UserType) {
            let user: UserType | null = localGetItem("regis_user");
            return ImitateHttp((s, f) => {
                if (!user) {
                    f("用户未注册");
                } else {
                    if (user.phone == form.phone && user.password == form.password) {
                        this.setUser(user);
                        s("登录成功");
                    } else {
                        s("手机号或密码错误");
                    }
                }
            });
        },
        getUser() {
            let data = localGetItem("login_user");
            if (data) {
                this.userInfo = data;
            }
        },
        logout() {
            localStorage.removeItem("login_user");
            this.userInfo = null;
        },

    }
})

export default userStore


